<?php

namespace app\tpush;

use app\system\model\Meta;
use Curl\Curl;

/**
 * 腾讯云移动推送
 */
class TPush
{
    /**
     * 同时发送 android 通知与穿透
     * @param $title 标题
     * @param $content 内容
     * @param $tokens 推送Tokens
     */
    public static function push($title, $content, $tokens)
    {
        self::notify($title, $content, $tokens);
        self::message($tokens);
    }

    /**
     * 只发送 android 穿透消息
     * @param $tokens 推送Tokens
     */
    public static function message($tokens)
    {
        $query = [
            'message_type' => 'message',
            'message' => [
                'title' => 'newMessage',
                'content' => 'newMessage',
            ],
            'audience_type' => 'token_list',
            'token_list' => $tokens,
        ];
        self::call($query);
    }

    /**
     * 只发送 android 通知
     * @param $title 标题
     * @param $content 内容
     * @param $tokens 推送Tokens
     */
    public static function notify($title, $content, $tokens)
    {
        $query = [
            'message_type' => 'notify',
            'message' => [
                'title' => $title,
                'content' => $content,
            ],
            'audience_type' => 'token_list',
            'token_list' => $tokens,
        ];
        self::call($query);
    }

    /**
     * 发送移动推送
     * @param $query 推送信息
     */
    public static function call($query)
    {
        $config = Meta::get('tpush');
        $AccessID = $config['accessId'];
        $SecretKey = $config['secretKey'];
        $timeStamp = time();
        $requestBody = json_encode($query);
        $hashData = $timeStamp . $AccessID . $requestBody;
        $hashRes = hash_hmac("sha256", $hashData, $SecretKey);
        $sign = base64_encode($hashRes);
        $curl = new Curl();
        $curl->setHeader('Content-Type', 'application/json');
        $curl->setHeader('AccessId', $AccessID);
        $curl->setHeader('TimeStamp', $timeStamp);
        $curl->setHeader('Sign', $sign);
        $curl->post('https://api.tpns.tencent.com/v3/push/app', $requestBody);
        $arr = json_decode($curl->rawResponse, true);
        return $arr['ret_code'] == 0 ? '' : $arr['err_msg']; // 发送失败则返回错误提示
    }
}
